package com.CGFrame.struts.bean.message;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import com.CGFrame.struts.POJOs.Confirmhistory;
import com.CGFrame.struts.POJOs.Message;
import com.CGFrame.struts.POJOs.Reguser;
import com.CGFrame.struts.bean.ProjectOperate;
import com.CGFrame.struts.bean.ProjectOperateFactory;
import com.CGFrame.struts.bean.reguser.ReguserBean;

public class MessageBean {
	private static ThreadLocal<MessageBean> mbTL=new ThreadLocal<MessageBean>();
	private String sender;
	private String receiver;
	private String content;
	private Date date;
	private boolean isRead;
	private String title;
	
	
	private MessageBean(){
	}
	
	public static MessageBean getMessageBean(){
		if(mbTL.get()==null){
			mbTL.set(new MessageBean());
		}
		return mbTL.get();
	}
	
	
	public String getTitle() {
		return title;
	}

	public boolean isRead() {
		return isRead;
	}

	public String getContent() {
		return content;
	}
	public Date getDate() {
		return date;
	}
	public String getReceiver() {
		return receiver;
	}
	public String getSender() {
		return sender;
	}
	
	public void send(String sender,String receiver,String title,String content,String imagePath){
		Timestamp timestamp=new Timestamp(new Date().getTime());
		Message message=new Message();
		message.setSender(sender);
		message.setReceiver(receiver);
		message.setTitle(title);
		message.setContent(content);
		message.setDate(timestamp);
		message.setIsRead(0);
		message.setImage(imagePath);
		ProjectOperate pop=ProjectOperateFactory.getprojectOperate();
		pop.saveObject(message);
	}
	
	public void sendWithImage(HttpServletRequest request) throws Exception{
		String receiver="";
		String copyer="";
		String title="";
		String content="";
		String reguserId=(String)request.getSession().getAttribute("RegUserID");
		String sender=new ReguserBean(reguserId).getEmpNameByReguserId();
		
		String temp=request.getSession().getServletContext().getRealPath("/"); //临时目录 
		String loadpath=request.getSession().getServletContext().getRealPath("/")+"message/image"; //上传文件
		DiskFileUpload fu = new DiskFileUpload();
		fu.setHeaderEncoding("utf-8");//上传中文名文件
		fu.setSizeMax(1*1024*1024*100); // 设置允许用户上传文件大小,单位:字节 
		fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节 
		fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录  
		StringBuffer imagePath=new StringBuffer();
		List fileItems = fu.parseRequest(request);
		Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件 
		int index=0;
		while (iter.hasNext()){ 
			FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息
			if (!item.isFormField()){
				String name = item.getName();//获取上传文件名,包括路径 
				name=name.substring(name.lastIndexOf("\\")+1);//从全路径中提取文件名 
				System.out.println("name:"+name);
				long size = item.getSize(); 
				if((name==null||name.equals("")) && size==0) 
					continue; 
				int point = name.indexOf("."); 
				name=(new Date()).getTime()+String.valueOf(index)+name.substring(point,name.length()); 
				imagePath.append(name).append(",");
				File fNew= new File(loadpath, name); 
				item.write(fNew);
				index++;
			}else{
				if(item.getFieldName().equals("receiver")){
					receiver=item.getString("utf-8");
				}
				if(item.getFieldName().equals("title")){
					title=item.getString("utf-8");
				}
				if(item.getFieldName().equals("content")){
					content=item.getString("utf-8");
				}
				if(item.getFieldName().equals("copyer")){
					copyer=item.getString("utf-8");
				}
			}
		}
		//如果标题为空,填写默认标题.
		if(title==null || title.length()==0){
			title="NO Subject";
		}
		if(receiver!=null && !receiver.equals("")){
			String[] receivers=receiver.split(",");
			for(int i=0;i<receivers.length;i++){
				send(sender, receivers[i],title,content,imagePath.toString());
			}
		}
		if(copyer!=null && !copyer.equals("")){
			String[] copyers=copyer.split(",");
			for(int i=0;i<copyers.length;i++){
				send(sender, copyers[i],title,content,imagePath.toString());
			}
		}
	}
	public ArrayList list(String userName){
		ProjectOperate pop=ProjectOperateFactory.getprojectOperate();
		List messageList= pop.Query("Message", "receiver,"+userName,"isRead","asc");
		ArrayList<HashMap> list=new ArrayList<HashMap>();
		Message message;
		int id;
		String sender;
		String receiver;
		String title;
		Date date;
		int isRead;
		for(Iterator iter=messageList.iterator();iter.hasNext();){
			HashMap messageMap=new HashMap();
			message=(Message)iter.next();
			id=message.getId();
			sender=message.getSender();
			receiver=message.getReceiver();
			title=message.getTitle();
			date=message.getDate();
			isRead=message.getIsRead();
			messageMap.put("id",id);
			messageMap.put("sender", sender);
			messageMap.put("receiver", receiver);
			messageMap.put("title", title);	
			messageMap.put("date", date);
			messageMap.put("isRead", isRead);
			list.add(messageMap);
		}
		return list;
	}
	
	public void delete(int[] ids,String imagePath){
		ProjectOperate pop=ProjectOperateFactory.getprojectOperate();
		for(int i=0;i<ids.length;i++){
			Message ms=(Message)pop.UniqueQuery("Message", "id,"+ids[i]);
			String[] images=ms.getImage().split(",");
			for(int j=0;j<images.length;j++){
				File a=new File(imagePath+"/"+images[j]);
				a.delete();
			}
			pop.deleteObject("Message",ids[i]);
		}
	}
	public HashMap showMessage(int id){
		ProjectOperate pop=ProjectOperateFactory.getprojectOperate();
		HashMap map=new HashMap();
		Message message=(Message)pop.UniqueQuery("Message", "id,"+id);
		message.setIsRead(1);
		map.put("id", message.getId());
		map.put("sender", message.getSender());
		map.put("receiver", message.getReceiver());
		map.put("title", message.getTitle());
		map.put("date", message.getDate());
		map.put("content", message.getContent());
		map.put("image", message.getImage());
		pop.saveObject(message);
		
		return map;
	}
}
